package com.xiaoxing.zhinenghuacangku_jining.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.zhinenghuacangku_jining.R;
import com.xiaoxing.zhinenghuacangku_jining.R2;
import com.xiaoxing.zhinenghuacangku_jining.di.component.DaggerJiNing_YiKuComponent;
import com.xiaoxing.zhinenghuacangku_jining.di.module.JiNing_YiKuModule;
import com.xiaoxing.zhinenghuacangku_jining.mvp.contract.JiNing_YiKuContract;
import com.xiaoxing.zhinenghuacangku_jining.mvp.model.entity.JiNing_GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_jining.mvp.presenter.JiNing_YiKuPresenter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.adapter.JiNing_ProductsAdapter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.adapter.JiNing_YiKuAdapter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_YiKu;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_YiKuGetStoreForLeaderResult;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ButtonUtils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_JINING_YI_KU)
public class JiNing_YiKuActivity extends BaseActivity<JiNing_YiKuPresenter> implements JiNing_YiKuContract.View {

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.nice_cang_ku)
    NiceSpinner mNiceCangKu;
    @BindView(R2.id.et_dan_hao)
    EditText mEtDanHao;
    @BindView(R2.id.et_xiang_mu_ming_cheng)
    AutoCompleteTextView mAutoCompleteTextViewProjects;
    @BindView(R2.id.et_wu_liao_ming_cheng)
    EditText mEtWuLiaoMingCheng;
    @BindView(R2.id.et_gong_ying_shang)
    EditText mEtGongYingShang;
    @BindView(R2.id.tv_cha_xun)
    TextView mTvChaXun;
    @BindView(R2.id.et_spname1)
    TextView mEtSpname1; //根据仓位查询要移库的数据
    private RecyclerView recyclerView;
    private JiNing_YiKuAdapter mAdapter;
    private List<JiNing_YiKu> mYiKuList = new ArrayList<>();
    private String mSname;
    private String mSid = "-1";
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private int spid = 0;
    private String spname = "";
    private String cangWeiPosition = "";
    private NiceSpinner nice_position;//弹出框下拉选
    private EditText et_weizhi;//弹出框位置填写输入框
    private boolean initProjects = true;
    private AlertDialog mAlertDialog;
    private SoapUtil soapUtil;
    private String mSelectedlikulinenumber;
    private String mSelecteddestinationSpname;

    public static List removeDuplicateWithOrder(List<JiNing_YiKu> list) {
//        Set set = new HashSet();
        List newList = new ArrayList();
//        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
//            Object element = iter.next();
//            if (set.add(element))
//                newList.add(element);
//        }

        List<String> newMaterialList = new ArrayList();
        //遍历数组往集合里存元素
        for (int i = 0; i < list.size(); i++) {
            //如果集合里面没有相同的元素才往里存
            if (!newMaterialList.contains(list.get(i).getMaterial())) {
                newMaterialList.add(list.get(i).getMaterial());
                newList.add(list.get(i));
            }
        }
        return newList;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mYiKuList = null;
        soapUtil = null;
        mAlertDialog = null;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerJiNing_YiKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .jiNing_YiKuModule(new JiNing_YiKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_ji_ning_activity_yi_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.zhi_neng_cang_ku_lin_yi_activity_yi_ku));
//        getYiKuData();

        soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);

        initEmpty();
        initRecyclerView();

        getStoreForLeader(mSharedPreferencesHelper.getString(BaseConstants.UID));
        getInventoryForLeader(mSharedPreferencesHelper.getString(BaseConstants.UID), mSid, "", "", "", "");
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 20, getResources().getColor(R.color.public_client_line_color)));
        mAdapter = new JiNing_YiKuAdapter(this, mYiKuList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

//                ArmsUtils.makeText(getContext(), "position=0" + position);

//                showXuanZeXinCangWei(mYiKuList.get(position).getMid(), mYiKuList.get(position).getIselecmeter(), mYiKuList.get(position).getLikulinenumber());
                showXuanZeXinCangWei(mYiKuList.get(position).getMid(), mYiKuList.get(position).getIselecmeter());
            }
        });

    }

    /**
     * 获取仓库列表
     *
     * @param user_id
     */
    private void getStoreForLeader(String user_id) {


        String methodName = "GetStoreForLeader";

        SoapParams params = new SoapParams();
        params.put("user_id", user_id);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {

                String result = object.getProperty("GetStoreForLeaderResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                    List<JiNing_YiKuGetStoreForLeaderResult> getStoreForLeaderResultList = new Gson().fromJson(result, new TypeToken<List<JiNing_YiKuGetStoreForLeaderResult>>() {
                    }.getType());

                    bindCangKuData(getStoreForLeaderResultList);
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    /**
     * 查询库存列表
     *
     * @param user_id     用户id
     * @param sid         仓库id
     * @param supplier    供应商
     * @param projectname 项目名称
     * @param purchaseid  订单号
     * @param material    物料名称
     */
    private void getInventoryForLeader(String user_id, String sid, String supplier, String projectname, String purchaseid, String material) {

        showLoading();

//        String methodName = "GetInventory";
//        String methodName = "GetInventoryQingDaoForMoveSpace";
        String methodName = "GetInventoryQingDaoForMove";

        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("sid", sid);
        params.put("supplier", supplier);
        params.put("projectname", projectname);
        params.put("purchaseid", purchaseid);
        params.put("material", material);
        params.put("spname", getEtSpname1());


        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<JiNing_YiKu> inventoryAndroidList = new Gson().fromJson(result, new TypeToken<List<JiNing_YiKu>>() {
                    }.getType());

                    if (inventoryAndroidList != null && inventoryAndroidList.size() > 0) {
                        if (!initProjects) {
                            mYiKuList.clear();
                            mYiKuList.addAll(inventoryAndroidList);
                            mAdapter.notifyDataSetChanged();
                            showData();
                        } else {
                            List<String> li_projects = new ArrayList<String>();
                            Set set = new HashSet();

//                            removeDuplicateWithOrder(inventoryAndroidList);
                            for (int i = 0; i < inventoryAndroidList.size(); i++) {
                                if (set.add(inventoryAndroidList.get(i).getProjectname()))
                                    li_projects.add(inventoryAndroidList.get(i).getProjectname());
                            }

                            mAutoCompleteTextViewProjects.setAdapter(new JiNing_ProductsAdapter(JiNing_YiKuActivity.this, R.layout.zhi_neng_cang_ku_ji_ning_item_projects, li_projects));
                        }
                    }

                } else {
                    hideData();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

                hideData();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                hideData();
            }
        }, getAapiUserName(), getApiPwd());


    }

    /**
     * 选择新仓位
     */
    private void showXuanZeXinCangWei(String mid, String iselecmeter) {

        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_ji_ning_layout_yi_ku_cang_wei_cha_xun, null);
        et_weizhi = myView.findViewById(R.id.et_weizhi);
        TextView tv_check = myView.findViewById(R.id.tv_check);
        nice_position = myView.findViewById(R.id.nice_position);
        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getUserSpaceListForAutoStore(getXinCangWei(), nice_position, iselecmeter);
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择新仓位");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {
                    if (TextUtils.isEmpty(spname)) {
                        ArmsUtils.makeText(getContext(), "请先选择新仓位");
                        return;
                    }
//                dialog.dismiss();
                    SendMaterialMoveOrder(mid, spname);
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    // 绑定仓库信息
    private void bindCangKuData(List<JiNing_YiKuGetStoreForLeaderResult> getStoreForLeaderResultList) {
        mNiceCangKu.setTextColor(Color.parseColor("#A8A8A8"));

        ArrayList<String> dataNames = new ArrayList();
        ArrayList<String> dataSids = new ArrayList();
        for (int i = 0; i < getStoreForLeaderResultList.size(); i++) {
            dataNames.add(getStoreForLeaderResultList.get(i).getSname());
            dataSids.add(String.valueOf(getStoreForLeaderResultList.get(i).getSid()));
        }
        mNiceCangKu.attachDataSource(dataNames);
        mSname = dataNames.get(0);
        mSid = dataSids.get(0);

        mNiceCangKu.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSname = dataNames.get(position);
                mSid = dataSids.get(position);
            }
        });

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @NonNull
    private String getEtSpname1() {
        return mEtSpname1.getText().toString().trim();
    }

    private void showData() {
        mEmptyLayout.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
    }

    private void hideData() {
        mEmptyLayout.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
    }

    /**
     * 查询可使用的（空闲）仓位
     *
     * @param spname     仓位名称
     * @param spPosition 下拉选
     */
    private void getUserSpaceListForAutoStore(String spname, NiceSpinner spPosition, String iselecmeter) {

        showLoading();

        String methodName = "GetUserSpaceListForAutoStoreQingDao";

        SoapParams params = new SoapParams();
        params.put("user_id", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("spname", spname);
        params.put("ismeter", iselecmeter);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                    List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = new Gson().fromJson(result, new TypeToken<List<JiNing_GetUserSpaceListForAutoStore>>() {
                    }.getType());

                    if (getUserSpaceListForAutoStoreList != null && getUserSpaceListForAutoStoreList.size() > 0) {
                        initSpPosition(getUserSpaceListForAutoStoreList, spPosition);
                    }
                } else {
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @NonNull
    private String getXinCangWei() {
        return et_weizhi.getText().toString().trim();
    }

    /**
     * 移库功能指令
     * <p>
     * //1--命令发送成功
     * //0--产生异常
     * //-1--目标仓位错误
     * //-2--源仓位库存为0
     * //-3--物料不存在
     * //-5，则提示正在移库中
     */
    private void SendMaterialMoveOrder(String mid, String destinationSpname) {

        showLoading();

        String methodName = "SendMaterialMoveOrderQingDao";

        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("destinationSpname", mSelecteddestinationSpname);
        params.put("likulinenumber", mSelectedlikulinenumber);

        LogUtils.debugEInfo("mid=" + mid);
        LogUtils.debugEInfo("destinationSpname=" + mSelecteddestinationSpname);
        LogUtils.debugEInfo("likulinenumber=" + mSelectedlikulinenumber);
        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {

                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (!TextUtils.isEmpty(result)) {

                    if (result.equals("1")) {
                        mAlertDialog.dismiss();
                        ArmsUtils.makeText(getContext(), "命令发送成功");
                    } else if (result.equals("0")) {
                        ArmsUtils.makeText(getContext(), "产生异常");
                    } else if (result.equals("-1")) {
                        ArmsUtils.makeText(getContext(), "目标仓位错误");
                    } else if (result.equals("-2")) {
                        ArmsUtils.makeText(getContext(), "源仓位库存为0");
                    } else if (result.equals("-3")) {
                        ArmsUtils.makeText(getContext(), "物料不存在");
                    } else if (result.equals("-4")) {
                        ArmsUtils.makeText(getContext(), "不同种类物品不能放入相同的立库");
                    } else if (result.equals("-5")) {
                        ArmsUtils.makeText(getContext(), "正在移库中");
                    }

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    /**
     * 初始化缓冲位列表下拉选
     */
    private void initSpPosition(List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList, NiceSpinner spPosition) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getUserSpaceListForAutoStoreList.get(i).getSpname())
            ));
        }
        spid = getUserSpaceListForAutoStoreList.get(0).getSpid();
        spname = list.get(0);
        cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(0).getSpid());
        mSelectedlikulinenumber = getUserSpaceListForAutoStoreList.get(0).getLikuLineNumber();
        mSelecteddestinationSpname = getUserSpaceListForAutoStoreList.get(0).getSpname();
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(position).getSpid());
                spid = getUserSpaceListForAutoStoreList.get(position).getSpid();
                spname = getUserSpaceListForAutoStoreList.get(position).getSpname();
                mSelectedlikulinenumber = getUserSpaceListForAutoStoreList.get(position).getLikuLineNumber();
                mSelecteddestinationSpname = getUserSpaceListForAutoStoreList.get(position).getSpname();

            }
        });
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private void getYiKuData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getYiKuData(map);
    }

    @Override
    public void getYiKuDataSuccess(JiNing_YiKu entityData) {


    }

    @OnClick(R2.id.tv_cha_xun)
    public void onViewClicked() {
        initProjects = false;
        String dingDanHao = mEtDanHao.getText().toString().trim();
        String xiangMuMingCheng = mAutoCompleteTextViewProjects.getText().toString().trim();
        String wuLiaoMingCheng = mEtWuLiaoMingCheng.getText().toString().trim();
        String gongYingShang = mEtGongYingShang.getText().toString().trim();
        getInventoryForLeader(mSharedPreferencesHelper.getString(BaseConstants.UID), mSid, gongYingShang, xiangMuMingCheng, dingDanHao, wuLiaoMingCheng);
    }

}
